/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author Ruby
 */
import java.util.Enumeration;
import java.util.Hashtable;

import javax.naming.Binding;
import javax.naming.Context;
import javax.naming.Name;
import javax.naming.NameClassPair;
import javax.naming.NameParser;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.BasicAttribute;
import javax.naming.directory.BasicAttributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import javax.naming.directory.ModificationItem;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;

public class LdapTest
{

    private static javax.naming.directory.DirContext getDirContext()
    {
        String account = "ruby";
        String password = "lizongbo";
        String root = "dc=ruby,dc=com"; // root

        Hashtable env = new Hashtable();
        env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        env.put(Context.PROVIDER_URL, "ldap://127.0.0.1/" + root);
        env.put(Context.SECURITY_AUTHENTICATION, "simple");
        env.put(Context.SECURITY_PRINCIPAL, "cn=Manager,dc=ruby,dc=com");
        env.put(Context.SECURITY_CREDENTIALS, password);

        DirContext ctx = null;
        try
        {
            // 链接ldap
            ctx = new InitialDirContext(env);
            System.out.println("ldap认证成功");
        } catch (NamingException err)
        {
            System.out.println(err);
        }
        return ctx;
    }

    /**
     * 返回用户查询接口
     * @param DN 查找范围 ou=test,dc=abcd,dc=com
     * @param filter 过滤条件 cn=*
     * @param myserach 搜索范围
     * @return LDAP标准接口
     * @throws Exception
     */
    public static javax.naming.NamingEnumeration getFilter(String DN, String filter, int myserach) throws Exception
    {
        DirContext ctx = getDirContext();
        try
        {
            NamingEnumeration em;
            SearchControls con = new SearchControls();
            con.setSearchScope(myserach);
            em = ctx.search(DN, filter, con);
            return em;
        } finally
        {//
        }
    }

    /**
     * 设置条件查找
     * @param dn 查找的根结点
     * @param filter 查找条件
     * @param level 查找范围
     * @return 返回一个由DN组成的JAVA STRING 列表
     * @throws Exception
     */
    public static java.util.Vector getfilterNodes(String dn, String filter, int level) throws Exception
    {
        java.util.Vector ve = new java.util.Vector();
        NamingEnumeration em = getFilter(dn, filter, level);
        while (em != null && em.hasMoreElements())
        {
            SearchResult rs = (SearchResult) em.nextElement();
            String db = rs.getName();
            if (db.trim().equals(""))
            {
                ve.add(dn);
            } else
            {
                ve.add(db + "," + dn);
            }
        }
        return ve;
    }

    public static void main(String[] args) throws Exception
    {
        DirContext dirContext = getDirContext();
//        getFilter("Manager", "", 1);
//        String dn = "uid=ruby,ou=People,o=com'";
//        Person p = new Person("ruby", "lizongbo", "sn", "givenname", "telNO", "mail", "department");
//        dirContext.bind(dn, p);
        // 链接ldap
//            ctx = new InitialDirContext(env);
//            System.out.println("ldap认证成功");

        // 3.添加节点
   String newUserName = "Manager2";
   BasicAttributes attrsbu = new BasicAttributes();
   BasicAttribute objclassSet = new BasicAttribute("objectclass");
   objclassSet.add("person");
   objclassSet.add("top");
   objclassSet.add("organizationalPerson");
   objclassSet.add("inetOrgPerson");
   attrsbu.put(objclassSet);
   attrsbu.put("sn",   newUserName);
   attrsbu.put("uid",   newUserName);
   dirContext.createSubcontext("cn=" + newUserName + ",ou=People", attrsbu);

        // 5.修改节点
//   account = "user2";
//   String newDisplayName = "newDisplayName";
//   ModificationItem modificationItem[] = new ModificationItem[1];
//   modificationItem[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, new BasicAttribute("displayName", newDisplayName));
//   ctx.modifyAttributes("cn=" + account, modificationItem);

        // 查询节点
//   SearchControls constraints = new SearchControls();
//   constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
//   // constraints.setSearchScope(SearchControls.ONELEVEL_SCOPE);
//   NamingEnumeration en = ctx.search("", "cn=Manager", constraints); // 查询所有用户
//   while (en != null && en.hasMoreElements()) {
//    Object obj = en.nextElement();
//    if (obj instanceof SearchResult) {
//     SearchResult si = (SearchResult) obj;
//     System.out.println("name:   " + si.getName());
//     Attributes attrs = si.getAttributes();
//     if (attrs == null) {
//      System.out.println("No   attributes");
//     } else {
//      for (NamingEnumeration ae = attrs.getAll(); ae.hasMoreElements();) {
//       Attribute attr = (Attribute) ae.next();
//       String attrId = attr.getID();
//
//       for (Enumeration vals = attr.getAll(); vals.hasMoreElements();) {
//        System.out.print(attrId + ":   ");
//        Object o = vals.nextElement();
//        if (o instanceof byte[])
//         System.out.println();// new
//               // String((byte[])o)
//        else
//         System.out.println(o);
//       }
//      }
//     }
//    } else {
//     System.out.println(obj);
//    }
//    System.out.println();
//   }

        // 4.删除节点
//   account = "user2";
//   ctx.destroySubcontext("cn=" + account);
//


        if (dirContext != null)
        {
            try
            {
                dirContext.close();
            } catch (NamingException e)
            {
                System.out.println("认证出错：" + e);
            }
        }
        System.exit(0);
    }
}

class Person implements DirContext
{

    public Person(String uid, String pwd, String sn, String givenname, String telNO, String mail, String department)
    {
        BasicAttributes newLdapUserAttrs = new BasicAttributes(true);

        Attribute objClass = new BasicAttribute("objectClass");
        objClass.add("inetorgperson");
        objClass.add("organizationalPerson");
        objClass.add("person");
        objClass.add("top");
        newLdapUserAttrs.put(objClass);

        Attribute ou = new BasicAttribute("ou");
        ou.add("People");
        newLdapUserAttrs.put(ou);

        System.out.println("put   Attribute!");
        String cn = sn + givenname;
        newLdapUserAttrs.put("uid", uid);
        newLdapUserAttrs.put("userPassword", pwd);
        newLdapUserAttrs.put("cn", cn);
        newLdapUserAttrs.put("sn", sn);
        newLdapUserAttrs.put("givenName", givenname);
        newLdapUserAttrs.put("departmentNumber", department);
        newLdapUserAttrs.put("telephoneNumber", telNO);
        newLdapUserAttrs.put("mail", mail);
        newLdapUserAttrs.put("preferredLanguage", "zh-CN");
    }

    @Override
    public Attributes getAttributes(Name name) throws NamingException
    {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public Attributes getAttributes(String name) throws NamingException
    {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public Attributes getAttributes(Name name, String[] attrIds) throws NamingException
    {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public Attributes getAttributes(String name, String[] attrIds) throws NamingException
    {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public void modifyAttributes(Name name, int mod_op, Attributes attrs) throws NamingException
    {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public void modifyAttributes(String name, int mod_op, Attributes attrs) throws NamingException
    {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public void modifyAttributes(Name name, ModificationItem[] mods) throws NamingException
    {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public void modifyAttributes(String name, ModificationItem[] mods) throws NamingException
    {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public void bind(Name name, Object obj, Attributes attrs) throws NamingException
    {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public void bind(String name, Object obj, Attributes attrs) throws NamingException
    {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public void rebind(Name name, Object obj, Attributes attrs) throws NamingException
    {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public void rebind(String name, Object obj, Attributes attrs) throws NamingException
    {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public DirContext createSubcontext(Name name, Attributes attrs) throws NamingException
    {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public DirContext createSubcontext(String name, Attributes attrs) throws NamingException
    {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public DirContext getSchema(Name name) throws NamingException
    {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public DirContext getSchema(String name) throws NamingException
    {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public DirContext getSchemaClassDefinition(Name name) throws NamingException
    {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public DirContext getSchemaClassDefinition(String name) throws NamingException
    {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public NamingEnumeration<SearchResult> search(Name name, Attributes matchingAttributes, String[] attributesToReturn) throws NamingException
    {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public NamingEnumeration<SearchResult> search(String name, Attributes matchingAttributes, String[] attributesToReturn) throws NamingException
    {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public NamingEnumeration<SearchResult> search(Name name, Attributes matchingAttributes) throws NamingException
    {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public NamingEnumeration<SearchResult> search(String name, Attributes matchingAttributes) throws NamingException
    {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public NamingEnumeration<SearchResult> search(Name name, String filter, SearchControls cons) throws NamingException
    {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public NamingEnumeration<SearchResult> search(String name, String filter, SearchControls cons) throws NamingException
    {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public NamingEnumeration<SearchResult> search(Name name, String filterExpr, Object[] filterArgs, SearchControls cons) throws NamingException
    {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public NamingEnumeration<SearchResult> search(String name, String filterExpr, Object[] filterArgs, SearchControls cons) throws NamingException
    {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public Object lookup(Name name) throws NamingException
    {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public Object lookup(String name) throws NamingException
    {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public void bind(Name name, Object obj) throws NamingException
    {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public void bind(String name, Object obj) throws NamingException
    {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public void rebind(Name name, Object obj) throws NamingException
    {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public void rebind(String name, Object obj) throws NamingException
    {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public void unbind(Name name) throws NamingException
    {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public void unbind(String name) throws NamingException
    {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public void rename(Name oldName, Name newName) throws NamingException
    {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public void rename(String oldName, String newName) throws NamingException
    {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public NamingEnumeration<NameClassPair> list(Name name) throws NamingException
    {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public NamingEnumeration<NameClassPair> list(String name) throws NamingException
    {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public NamingEnumeration<Binding> listBindings(Name name) throws NamingException
    {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public NamingEnumeration<Binding> listBindings(String name) throws NamingException
    {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public void destroySubcontext(Name name) throws NamingException
    {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public void destroySubcontext(String name) throws NamingException
    {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public Context createSubcontext(Name name) throws NamingException
    {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public Context createSubcontext(String name) throws NamingException
    {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public Object lookupLink(Name name) throws NamingException
    {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public Object lookupLink(String name) throws NamingException
    {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public NameParser getNameParser(Name name) throws NamingException
    {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public NameParser getNameParser(String name) throws NamingException
    {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public Name composeName(Name name, Name prefix) throws NamingException
    {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public String composeName(String name, String prefix) throws NamingException
    {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public Object addToEnvironment(String propName, Object propVal) throws NamingException
    {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public Object removeFromEnvironment(String propName) throws NamingException
    {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public Hashtable<?, ?> getEnvironment() throws NamingException
    {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public void close() throws NamingException
    {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public String getNameInNamespace() throws NamingException
    {
        throw new UnsupportedOperationException("Not supported yet.");
    }
}